package com.zhengtoudai.base;


import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.zhengtoudai.R;
import com.zhengtoudai.view.CustomViewPager;
import com.zhengtoudai.view.swipetoloadlayout.base.SwipeToLoadLayout;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 滑动fragment
 * <p/>
 * xiejingwen
 */
public abstract class BaseViewPagerFragment extends BaseFragment implements AppBarLayout.OnOffsetChangedListener,ViewPager.OnPageChangeListener{
    @Bind(R.id.viewpager)
    CustomViewPager viewpager;
    @Bind(R.id.tab_layout)
    TabLayout mTabLayout;
    @Bind(R.id.appbar)
    AppBarLayout mAppbar;

    private String[] titles;
    private Fragment[] fragments;

    private PagerAdapter mAdapter;

    private SwipeToLoadLayout mRefresh;

    //主题颜色  （选中颜色）
    private int colorStyle = R.color.title_text;
    //未选中颜色
    protected int normalTextColor = R.color.black_3;

    private int background = R.color.white; //背景颜色

    protected abstract String[] getTitles();

    protected abstract Fragment[] getFragments();

    //若需使用其他颜色，复写该方法即可
    protected int ColorStyle() {
        return colorStyle;
    }


    protected abstract void initTitle();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getContext();
        View view = inflater.inflate(R.layout.fragment_base_view_pager, container, false);
        ButterKnife.bind(this, view);
        super.onCreateView(inflater, container, savedInstanceState);
        return view;
    }


    /**
     * 设置背景颜色
     *
     * @param background 传入颜色ResId
     */
    protected void setBackground(int background) {
        this.background = background;
    }

    /**
     * 设置未选中Tab字体颜色
     *
     * @param TextColor 传入颜色ResId
     */
    protected void setNormalTextColor(int TextColor) {
        this.normalTextColor = TextColor;
    }

    /**
     * 设置ViewPager缓存数量
     *
     * @param pageLimit
     */
    public void setViewpagerSlide(int pageLimit) {
        viewpager.setOffscreenPageLimit(pageLimit);
    }

    /**
     * onCreatePost 之后调用
     * 设置文字
     */
    protected void setTabText(int position, String text) {
        mTabLayout.getTabAt(position).setText(text);
    }

    @Override
    protected void initView() {
        titles = getTitles();
        colorStyle = ColorStyle();
        fragments = getFragments();

        mTabLayout.setBackgroundResource(background);
        mTabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(mContext, colorStyle));
        mTabLayout.setTabTextColors(ContextCompat.getColor(mContext, normalTextColor), ContextCompat.getColor(mContext, colorStyle));

        for (int i = 0; i < titles.length; i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(titles[i]));
        }
        mAdapter = new PagerAdapter(fragments, titles, getChildFragmentManager());
        viewpager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(viewpager);
        viewpager.post(new Runnable() {
            @Override
            public void run() {
                getSwipeToLoadLayout((ViewGroup) mAdapter.getItem(viewpager.getCurrentItem()).getView());
            }
        });


    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mRefresh=null;
        getSwipeToLoadLayout((ViewGroup) mAdapter.getItem(position).getView());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    @Override
    public void onResume() {
        super.onResume();
        mAppbar.addOnOffsetChangedListener(this);
        viewpager.addOnPageChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        mAppbar.removeOnOffsetChangedListener(this);
        viewpager.removeOnPageChangeListener(this);
    }

    private void getSwipeToLoadLayout(ViewGroup parent) {
        if (parent==null){
            return;
        }
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            if (child instanceof SwipeToLoadLayout) {
                mRefresh=(SwipeToLoadLayout) child;
                return;
            } else if (child instanceof ViewGroup) {
                getSwipeToLoadLayout((ViewGroup) child);
            }
        }
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (mRefresh==null){
            return;
        }
        if (verticalOffset==0){
           mRefresh.setRefreshEnabled(true);
        }else{
            mRefresh.setRefreshEnabled(false);
        }
    }

    /**
     * 是否禁止viewpager滑动 默认可以滑动
     *
     * @param isSlide
     */
    public void setViewpagerSlide(boolean isSlide) {
        viewpager.setScanScroll(isSlide);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    static class PagerAdapter extends FragmentPagerAdapter {
        private Fragment[] fragments;
        private String[] titles;

        public PagerAdapter(Fragment[] fragments, String[] titles, FragmentManager fm) {
            super(fm);
            this.fragments = fragments;
            this.titles = titles;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments[position];
        }

        @Override
        public int getCount() {
            return fragments.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}
